import { useState, useEffect } from 'react';
import Req from '@/utils/request';

// eslint-disable-next-line import/prefer-default-export
export const useTable = ({ api }) => {
    const [loading, setLoading] = useState(false);
    const [total, setTotal] = useState(0);
    const [pageIndex, setPageIndex] = useState(0);
    const [pageSize, setPageSize] = useState(10);
    const [data, setData] = useState([]);
    const [searchData, setSearch] = useState({});

    const init = (current, size) => {
        setLoading(true);
        const params = {
            pageIndex: current,
            pageSize: size,
            ...searchData,
        };

        api(params).then((res) => {
            console.log(res, '请求结果')
            setLoading(false);
            setData(res.results);
            setTotal(res.results.length);
        });
    };

    const handleChangePage = (current, size) => {
        setPageIndex(current);
        setPageSize(size || pageSize);
        init(current, size || pageSize);
    };

    useEffect(() => {
        init(1, 10);
    }, []);

    useEffect(() => {
        handleChangePage(1, 10);
    }, [searchData]);

    return {
        setSearch,
        loading,
        total,
        pageIndex,
        pageSize,
        data,
        handleChangePage,
    };
};
